<?php
include("define.php");
include("defineFunc.php");
$config = json_decode(file_get_contents("config.json"),true);
$pre = c("prefix")."-";
$messageList = [
    I01=>"执行成功",
    E01=>"操作参数不正确",
    E02=>P01.S01,
    E03=>P02.S01,
    E04=>P05.S01,
    E05=>P06.S01,
    E06=>"文件读取失败",
    E07=>"文件写入失败",
    E08=>"接口秘钥不正确",
    E09=>"VM-Rest服务通信失败，服务可能没有启动或API配置有误",
    E10=>"无法找到该ID对应的机器",
    E11=>"该机器的硬盘似乎丢了",
    E12=>"节点内存不足"
];
/**
 * 返回请求参数
 * @param $n
 * @return mixed|string
 */
function a($n){
    return $_REQUEST[$n]??"";
}

/**
 * 返回配置
 * @param $n
 * @return mixed|string
 */
function c($n){
    global $config;
    return $config[$n]??"";
}

/**
 * 发送请求
 * @param $a
 * @param mixed ...$arg
 * @return string
 */
function r($a,...$arg):string{
    $host = c("host");
    $port = c("port");
    $auth = c("token");
    exec(f($a,$auth,$host,$port,@$arg[0],@$arg[1],@$arg[2],@$arg[3]),$b);
    $b = join("",$b);
    if (strlen($b)===0){
        b(E09);
    }
    $c = json_decode($b,true);
    if (isset($c["Message"])){
        if ($c["Message"] == "Authentication failed") {
            b(E08);
        }
    }
    return $b;
}

/**
 * 格式化字符串
 * @param $a
 * @param ...$arg
 * @return string
 */
function f($a,...$arg): string
{
    return sprintf($a,@$arg[0],@$arg[1],@$arg[2],@$arg[3],@$arg[4],@$arg[5]);
}

/**
 * 返回数据
 * @param $code
 * @param bool $die
 * @return void
 */
function b($code, bool $die=true,$data=""){
    global $messageList;
    $status = substr($code,0,1)!="E";
    $message = $messageList[$code];
    if (a("type")=="text"){
        echo $message;
        if (!empty($data)){
            echo "<br>";
            var_dump($data);
        }
    }else {
        $error_code = "";
        if ($code===E08){
            $error_code = "token-error";
        }
        print(json_encode(["status" => $status, "msg" => $message,"error"=>$error_code,"data"=>$data]));
    }
    if ($die)die();
}

/**
 * 服务器操作系统类型
 * @return string
 */
function o():string{
    if(strlen(strstr(php_uname(),"Windows"))>0){
        return "Windows";
    }else{
        return "Linux";
    }
}
